<template>
    <div class="el-container">
        <div class="blank-card">
            <!--部门数据-->
            <div class="head-container">
                <el-input v-model="deptName" :placeholder="$t('public.placeholder',{placeholder:$t('deptManage.deptName')})" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container deptLine">
                <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
            </div>
        </div>
        <div class="fold-bar"></div>
        <div class="app-container">
            <div class="searchAll">
                <el-form :model="queryParams" ref="queryForm" label-position="right" v-show="showSearch" label-width="70px">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item :label="$t('userManage.userName')" prop="userName">
                                <el-input v-model="queryParams.userName" :placeholder="$t('public.placeholder',{placeholder:$t('userManage.userName')})" clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('userManage.phone')" prop="phonenumber">
                                <el-input v-model="queryParams.phonenumber" :placeholder="$t('public.placeholder',{placeholder:$t('userManage.phone')})" clearable size="small" @keyup.enter.native="handleQuery" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('public.status')" prop="status">
                                <el-select v-model="queryParams.status" :placeholder="$t('public.select_holder',{select_holder: $t('userManage.userStu')})" clearable size="small">
                                    <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('public.createTime')">
                                <el-date-picker v-model="dateRange" size="small" style="width: 100%" value-format="yyyy-MM-dd" type="daterange" autocomplete="off" range-separator="-" :start-placeholder="$t('public.startDate')" :end-placeholder="$t('public.endDate')"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="厂区" prop="factoryName">
                                <el-select style="width:100%" v-model="queryParams.factoryName" multiple filterable size="small" placeholder="请输入厂区名称" :loading="loading">
                                    <el-option v-for="item in factoryOptions" :key="item.id" :label="item.factoryName" :value="item.factoryName">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <div class="searchAres searchAresHeng">
                                <el-button type="primary" icon="el-icon-search" size="mini" class="searchBtn" @click="handleQuery">{{ $t("public.query") }}</el-button>
                                <el-button class="resectBtn" icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("public.reset") }}</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="tableList">
                <div class="insTitle">
                    <span>{{ $t("systemTitle.userManagement") }}</span>
                </div>
                <div class="btnGroup">
                    <el-button v-hasPermi="['tenant:user:add']" type="primary" icon="el-icon-plus" size="mini" class="additemBtn" @click="handleAdd">{{ $t("public.add") }}</el-button>
                    <el-button v-hasPermi="['tenant:user:remove']" icon="el-icon-delete" size="mini" class="deleteitemBtn" :disabled="multiple" @click="handleDelete">{{ $t("public.delete") }}</el-button>
                    <el-button v-hasPermi="['system:saas:user:import']" class="importitemBtn" size="mini" @click="handleImport"><img src="../../../assets/images/icons/daoru.png" alt=""> {{ $t("public.import") }}</el-button>
                    <el-button v-hasPermi="['system:saas:user:export']" class="exportitemBtn" size="mini" @click="handleExport"><img src="../../../assets/images/icons/daochu.png" alt=""> {{ $t("public.export") }}</el-button>
                </div>
                <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="50" align="center" />

                    <el-table-column :label="$t('userManage.userCode')" width="160" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
                    <el-table-column :label="$t('userManage.userName')" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('userManage.loginName')" align="center" key="loginName" prop="loginName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('userManage.dept')" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
                    <el-table-column label="所在厂区" align="center" key="factoryName" prop="factoryName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
                    <el-table-column :label="$t('userManage.phone')" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible" width="120" />

                    <el-table-column :label="$t('public.status')" align="center" key="status" v-if="columns[5].visible">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('public.createTime')" align="center" prop="createTime" v-if="columns[6].visible" width="160">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('public.opera')" fixed="right" align="center" min-width="200">
                        <template slot-scope="scope" v-if="scope.row.userId !== 1">
                            <div>
                                <table-body-btn type="gwview" :name="$t('public.detail')" @click.native="handleView(scope.row)" v-hasPermi="['tenant:user:query']" />
                                <table-body-btn type="gwedit" :name="$t('public.edit')" @click.native="handleUpdate(scope.row)" v-hasPermi="['tenant:user:edit']" />
                                <table-body-btn type="gwdelete" :name="$t('public.delete')" @click.native="handleDelete(scope.row)" v-hasPermi="['tenant:user:remove']" />
                                <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
                                    <span class="el-dropdown-link">
                                        <table-body-btn type="more" />
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item command="handleResetPwd" icon="el-icon-key" v-hasPermi="['system:user:resetPwd']">重置密码</el-dropdown-item>
                                        <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check" v-hasPermi="['system:user:edit']">分配角色</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
            </div>

            <!--      </el-col>-->
            <!--    </el-row>-->

            <!-- 添加或修改用户配置对话框 -->
            <el-dialog :title="title" :visible.sync="open" v-if="open" width="700px" append-to-body :fullscreen="fullscreen">
                <DialogTit slot="title" :title="title" :fullscreen.sync="fullscreen"></DialogTit>
                <el-form ref="userConfigForm" :model="userConfigForm" :rules="rules" label-width="100px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item :label="$t('userManage.loginName')" prop="loginName" size="small">
                                <el-input v-model="userConfigForm.loginName" :disabled="dialogType>2||userConfigForm.userId != undefined" autocomplete="off" :placeholder="$t('public.placeholder',{placeholder:$t('userManage.loginName')})" maxlength="30" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="$t('userManage.userPass')" prop="password" size="small">
                                <el-input v-model="userConfigForm.password" :disabled="dialogType>1" autocomplete="off" :placeholder="$t('public.placeholder',{placeholder:$t('userManage.userPass')})" type="password" maxlength="20" show-password />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item :label="$t('userManage.userName')" prop="userName" size="small">
                                <el-input v-model="userConfigForm.userName" :disabled="dialogType>2" :placeholder="$t('public.placeholder',{placeholder:$t('userManage.userName')})" maxlength="30" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="$t('userManage.belongDept')" prop="deptId" size="small">
                                <treeselect @input="deptIdChange" :disabled="dialogType>2" v-model="userConfigForm.deptId" :options="deptOptions" :show-count="true" :placeholder="$t('public.placeholder',{placeholder:$t('userManage.belongDept')})" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item :label="$t('userManage.phone')" prop="phonenumber" size="small">
                                <el-input :disabled="dialogType>2" v-model="userConfigForm.phonenumber" :placeholder="$t('public.placeholder',{placeholder:$t('userManage.phone')})" maxlength="11" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="$t('public.email')" prop="email" size="small">
                                <el-input :disabled="dialogType>2" v-model="userConfigForm.email" :placeholder="$t('public.placeholder',{placeholder:$t('public.email')})" maxlength="50" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item :label="$t('userManage.userGender')" size="small">
                                <el-select :disabled="dialogType>2" style="width:100%;" v-model="userConfigForm.sex" :placeholder="$t('public.select_holder',{select_holder: $t('userManage.userGender')})">
                                    <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="$t('public.status')" size="small">
                                <el-radio-group :disabled="dialogType>2" v-model="userConfigForm.status">
                                    <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item :label="$t('userManage.post')" size="small">
                                <el-select :disabled="dialogType>2" style="width:100%;" v-model="userConfigForm.postIds" multiple :placeholder="$t('public.select_holder',{select_holder: $t('userManage.post')})">
                                    <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId" :disabled="item.status == 1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item :label="$t('userManage.role')" prop="roleIds" size="small">
                                <el-select :disabled="dialogType>2" style="width:100%;" v-model="userConfigForm.roleIds" multiple :placeholder="$t('public.select_holder',{select_holder: $t('userManage.role')})">
                                    <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="item.status == 1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="所在厂区" size="small" prop="factoryName">
                            <el-tooltip effect="dark" :disabled="userConfigForm.factoryName?false:true" :content="userConfigForm.factoryName" placement="top-start">
                                <plant-area-select placeholder="请选择厂区" :disabled="dialogType === 3" multiple style="width:100%" @callback="(val) => factoryNameCallback(val)" v-model="userConfigForm.factoryName" />
                            </el-tooltip>
                        </el-form-item>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item :label="$t('public.remark')" size="small">
                                <el-input :disabled="dialogType>2" v-model="userConfigForm.remark" type="textarea" :placeholder="$t('public.placeholder',{placeholder:$t('public.remark')})"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel" icon="el-icon-close" size="small">{{$t('public.cancel')}}</el-button>
                    <el-button type="primary" v-if="dialogType != 3" @click="submitForm" icon="el-icon-check" size="small">{{$t('public.define')}}</el-button>
                </div>
            </el-dialog>

            <!-- 用户导入对话框 -->
            <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
                <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">{{$t('formValidation.dragFilesHere')}}&nbsp;{{$t('formValidation.or')}}<em>{{$t('formValidation.clickToUpload')}}</em></div>
                    <div class="el-upload__tip text-center" slot="tip">
                        <div class="el-upload__tip" slot="tip">
                            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                        </div>
                        <span>{{$t('formValidation.onlyXlsXlsx')}}</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">{{ $t('formValidation.downloadTemplate') }}</el-link>
                    </div>
                </el-upload>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="upload.open = false" icon="el-icon-close" size="small">取 消</el-button>
                    <el-button type="primary" @click="submitFileForm" icon="el-icon-check" size="small">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {
    listUser,
    getUser,
    delUser,
    addUser,
    updateUser,
    resetUserPwd,
    changeUserStatus,
} from '@/api/system/user'
import { getToken } from '@/utils/auth'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import ListLayout from '@/layout/ListLayout'
import { listALLFactory } from '@/api/basic/factory'
import plantAreaSelect from '@/views/components/plantAreaSelect'
export default {
    name: 'User',
    dicts: ['sys_normal_disable', 'sys_user_sex'],
    components: { Treeselect, ListLayout, plantAreaSelect },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            userList: null,
            // 弹出层标题
            title: '',
            // 弹出层类型
            opraType: '',
            // 部门树选项
            deptOptions: undefined,
            // 是否显示弹出层
            open: false,
            dialogType: 1, //1新增 2修改
            // 部门名称
            deptName: undefined,
            // 默认密码
            initPassword: undefined,
            // 日期范围
            dateRange: [],
            // 岗位选项
            postOptions: [],
            // 角色选项
            roleOptions: [],
            // 表单参数
            userConfigForm: {
                factoryCode: [],
                factoryName: [],
            },
            factoryOptions: [],
            defaultProps: {
                children: 'children',
                label: 'label',
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url:
                    process.env.VUE_APP_BASE_API +
                    '/system/saas/user/importData',
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                factoryName: [],
                userName: undefined,
                phonenumber: undefined,
                status: undefined,
                deptId: undefined,
            },
            // 列信息
            columns: [
                { key: 0, label: `用户编号`, visible: true },
                { key: 1, label: `用户名称`, visible: true },
                { key: 2, label: `用户昵称`, visible: true },
                { key: 3, label: `部门`, visible: true },
                { key: 4, label: `手机号码`, visible: true },
                { key: 5, label: `状态`, visible: true },
                { key: 6, label: `创建时间`, visible: true },
            ],
            // 表单校验
            rules: {
                userName: [
                    {
                        required: true,
                        message: '用户名称不能为空',
                        trigger: 'blur',
                    },
                    {
                        min: 2,
                        max: 20,
                        message: '用户名称长度必须介于 2 和 20 之间',
                        trigger: 'blur',
                    },
                ],
                loginName: [
                    {
                        required: true,
                        message: '登录名称不能为空',
                        trigger: 'blur',
                    },
                ],
                deptId: [
                    {
                        required: true,
                        message: '部门不能为空',
                        trigger: 'change',
                    },
                ],
                roleIds: [
                    {
                        required: true,
                        message: '角色不能为空',
                        trigger: 'change',
                    },
                ],
                password: [
                    {
                        required: true,
                        message: '用户密码不能为空',
                        trigger: 'blur',
                    },
                    {
                        min: 5,
                        max: 20,
                        message: '用户密码长度必须介于 6 和 20 之间',
                        trigger: 'blur',
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (this.opraType === 'add') {
                                var pwdRegex = new RegExp(
                                    '(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,20}'
                                )
                                if (!pwdRegex.test(value)) {
                                    return callback(
                                        new Error(
                                            '密码中必须包含字母、数字、特称字符!'
                                        )
                                    )
                                }
                                callback()
                            } else {
                                callback()
                            }
                        },
                        trigger: 'blur',
                    },
                ],
                email: [
                    {
                        type: 'email',
                        message: "'请输入正确的邮箱地址",
                        trigger: ['blur', 'change'],
                    },
                ],
                phonenumber: [
                    {
                        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                        message: '请输入正确的手机号码',
                        trigger: 'blur',
                    },
                ],
            },
            fullscreen: false,
            names: [],
            // 是否全选
            checked: false,
        }
    },
    watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val)
        },
        checked(val) {
            if (val) {
                this.userConfigForm.factoryName = this.factoryOptions.map(
                    (el) => el.factoryName
                )
            } else {
                this.userConfigForm.factoryName = []
            }
        },
    },
    created() {
        this.getList()
        this.getFactoryOpts()
        this.getTreeselect()
        this.getConfigKey('sys.user.initPassword').then((response) => {
            this.initPassword = response.msg
        })
    },
    methods: {
        /** 重置密码按钮操作 */
        handleResetPwd(row) {
            this.$prompt('请输入"' + row.userName + '"的新密码', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                inputPattern: /^.{5,20}$/,
                inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
            })
                .then(({ value }) => {
                    resetUserPwd(row.userId, value).then((response) => {
                        this.$modal.msgSuccess('修改成功，新密码是：' + value)
                    })
                })
                .catch(() => {})
        },
        /** 分配角色操作 */
        handleAuthRole: function (row) {
            const userId = row.userId
            this.$router.push('/system/user-auth/role/' + userId)
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case 'handleResetPwd':
                    this.handleResetPwd(row)
                    break
                case 'handleAuthRole':
                    this.handleAuthRole(row)
                    break
                default:
                    break
            }
        },
        filterParams(p) {
            if (p && p.length) {
                return p.join(';')
            } else {
                return ''
            }
        },
        /** 查询用户列表 */
        getList() {
            this.loading = true
            let params = JSON.parse(JSON.stringify(this.queryParams))
            params.factoryName = this.filterParams(params.factoryName)
            listUser(this.addDateRange(params, this.dateRange)).then(
                (response) => {
                    this.userList = response.rows
                    this.total = response.total
                    this.loading = false
                }
            )
        },
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data
            })
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        factoryNameCallback(val) {
            this.userConfigForm.factoryCode = val
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams.deptId = data.id
            this.getList()
        },
        // 用户状态修改
        handleStatusChange(row) {
            let text =
                row.status === '0'
                    ? this.$t('public.enable')
                    : this.$t('public.disable')
            this.$modal
                .confirm(
                    this.$t('public.preEnableConfirm', {
                        key: text,
                        value: row.userName,
                    })
                )
                .then(function () {
                    return changeUserStatus(row.userId, row.status)
                })
                .then(() => {
                    this.$modal.msgSuccess(text + this.$t('public.success'))
                })
                .catch(function () {
                    row.status = row.status === '0' ? '1' : '0'
                })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.userConfigForm = {
                userId: undefined,
                deptId: undefined,
                userName: undefined,
                loginName: undefined,
                password: undefined,
                phonenumber: undefined,
                email: undefined,
                sex: undefined,
                status: '0',
                remark: undefined,
                postIds: [],
                roleIds: [],
            }
            this.resetForm('userConfigForm')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.queryParams.deptId = undefined
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.userId)
            this.names = selection.map((item) => item.userName)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case 'handleResetPwd':
                    this.handleResetPwd(row)
                    break
                case 'handleAuthRole':
                    this.handleAuthRole(row)
                    break
                default:
                    break
            }
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.dialogType = 1
            this.open = true
            this.getTreeselect()
            getUser().then((response) => {
                this.postOptions = response.posts
                this.roleOptions = response.roles
                this.title = this.$t('userManage.addUser')
                this.opraType = 'add' //操作是添加
                this.userConfigForm.password = this.initPassword
            })
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            this.dialogType = 2
            this.title = '修改用户'
            this.open = true
            this.getTreeselect()
            const userId = row.userId || this.ids
            getUser(userId).then((response) => {
                this.userConfigForm = response.data
                this.postOptions = response.posts
                this.roleOptions = response.roles
                this.userConfigForm.postIds = response.postIds
                this.userConfigForm.roleIds = response.roleIds

                this.title = this.$t('userManage.modUser')
                this.opraType = 'edit' //操作是修改
                this.userConfigForm.password = '******'
            })
        },
        handleView(row) {
            this.reset()
            this.dialogType = 3
            this.open = true
            this.getTreeselect()
            const userId = row.userId || this.ids
            getUser(userId).then((response) => {
                this.userConfigForm = response.data
                this.postOptions = response.posts
                this.roleOptions = response.roles
                this.userConfigForm.postIds = response.postIds
                this.userConfigForm.roleIds = response.roleIds
                this.title = '用户详情'
                this.opraType = 'edit' //操作是修改
                this.userConfigForm.password = '******'
            })
        },
        /** 重置密码按钮操作 */
        handleResetPwd(row) {
            // this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
            this.$prompt(
                this.$t('userManage.passwordTip', { value: row.userName }),
                this.$t('public.tip'),
                {
                    confirmButtonText: this.$t('public.define'),
                    cancelButtonText: this.$t('public.cancel'),
                    closeOnClickModal: false,
                    inputPattern: /^.{5,20}$/,
                    inputErrorMessage: this.$t('userManage.passwordValTip'),
                }
            )
                .then(({ value }) => {
                    resetUserPwd(row.userId, value).then((response) => {
                        this.$modal.msgSuccess(
                            this.$t('userManage.passwordSucTip', { value })
                        )
                    })
                })
                .catch(() => {})
        },
        /** 分配角色操作 */
        handleAuthRole: function (row) {
            const userId = row.userId
            // this.$router.push("/tenant/user-auth/role/" + userId);
            this.$router.push({
                path: '/tenant/user-auth/role',
                query: { userId },
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs['userConfigForm'].validate((valid) => {
                if (valid) {
                    let params = { ...this.userConfigForm }
                    if (params.userId != undefined) {
                        delete params.password
                        updateUser(params).then((response) => {
                            this.$modal.msgSuccess(this.$t('formValidation.successfullyModified'))
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addUser(params).then((response) => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const userIds = row.userId || this.ids
            const names = row.userName || this.names
            // this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function() {
            this.$modal
                .confirm(
                    this.$t('public.preConfirm', {
                        key: this.$t('userManage.userName'),
                        value: names,
                    })
                )
                .then(function () {
                    return delUser(userIds)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess(this.$t('processDefinition.successfullyDeleted'))
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            let params = JSON.parse(JSON.stringify(this.queryParams))
            params.factoryName = this.filterParams(params.factoryName)
            this.download(
                'system/saas/user/export',
                {
                    ...this.addDateRange(params, this.dateRange),
                },
                `user_${new Date().getTime()}.xlsx`
            )
        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = '用户导入'
            this.upload.open = true
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download(
                'system/saas/user/importTemplate',
                {},
                `user_template_${new Date().getTime()}.xlsx`
            )
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false
            this.upload.isUploading = false
            this.$refs.upload.clearFiles()
            this.$alert(response.msg, '导入结果', {
                dangerouslyUseHTMLString: true,
            })
            this.getList()
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit()
        },
        getFactoryOpts(factoryName) {
            let data = {}
            if (factoryName) {
                data.factoryName = factoryName
            }
            listALLFactory(data).then((res) => {
                if (res.code == 200) {
                    this.factoryOptions = res.data
                }
            })
        },
        deptIdChange(val) {
            if (val) {
                this.$refs.userConfigForm.validateField('deptId')
            }
        },
        handleFactoryChange(e) {
            console.log(e)
            this.userConfigForm.factoryName = e
            this.$set(this.userConfigForm, 'factoryName', e)
        },
        handleFactoryQueryChange(e) {
            this.queryParams.factoryName = e.join(',')
        },
    },
}
</script>
<style lang="scss" scoped>
.deptLine {
    height: calc(100vh - 170px);
    overflow-y: scroll;
}
.el-container {
    display: flex;
    flex-direction: row;
    flex: 1;
    flex-basis: auto;
    box-sizing: border-box;
    min-width: 0;
}
.app-container {
    border: 1px solid #d7dde4;
    border-radius: 2px;
    background-color: #fff;
    display: block;
    flex: 1;
    flex-basis: auto;
    overflow: auto;
}
.blank-card {
    padding: 15px;
    background: #fff;
}
.fold-bar {
    position: relative;
    width: 10px;
    height: 100%;
}
</style>



